//
//  DYPushCenter.m
//  singlePushDemo
//
//  Created by JM on 15/10/10.
//  Copyright © 2015年 JM. All rights reserved.
//

#import "DYPushCenter.h"
#import "DYSMSCenter.h"



#if DYISocketLogSwith
#define DYISocketLog(format, ...) NSLog(format, ##__VA_ARGS__)
#else
#define DYISocketLog(format, ...) {}
#endif

//IOS8的 新的特性  暂未使用
//#define NotifyActionKey "NotifyAction"
static NSString* const NotificationCategoryIdent  = @"ACTIONABLE";
static NSString* const NotificationActionOneIdent = @"ACTION_ONE";
static NSString* const NotificationActionTwoIdent = @"ACTION_TWO";

@interface DYPushCenter ()<GeTuiSdkDelegate>
@property(nonatomic,retain) NSString *deviceToken;//个推透穿过来的数据
@property (copy, nonatomic) NSString *payloadId;////根据 payloadId 取回 Payload（payloadMsg）
@property (assign, nonatomic) SdkStatus *sdkStatus;//个推的状态

@property(nonatomic,copy)HandleRegisterBlock regisierblock;
@property(nonatomic,assign)BOOL haveInit;


- (void)active:(NSError **)err;
- (void)sleep;//等待active激活后 再次接收消息
@end

@implementation DYPushCenter
singleton_implementation(DYPushCenter)

- (id)init {
    if (self = [super init]) {
        //根据个推的范例来的
        [self active:nil];
        // 创建 通知类型
        [DYSMSCenter createSMSType:DYPushCenter_Message];
    }
    return self;
}

#pragma -mark  注册APNS
- (void)registerRemoteNotification {
    
#ifdef __IPHONE_8_0
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        //IOS8 新的通知机制category注册
        UIMutableUserNotificationAction *action1;
        action1 = [[UIMutableUserNotificationAction alloc] init];
        [action1 setActivationMode:UIUserNotificationActivationModeBackground];
        [action1 setTitle:@"取消"];
        [action1 setIdentifier:NotificationActionOneIdent];
        [action1 setDestructive:NO];
        [action1 setAuthenticationRequired:NO];
        
        UIMutableUserNotificationAction *action2;
        action2 = [[UIMutableUserNotificationAction alloc] init];
        [action2 setActivationMode:UIUserNotificationActivationModeBackground];
        [action2 setTitle:@"回复"];
        [action2 setIdentifier:NotificationActionTwoIdent];
        [action2 setDestructive:NO];
        [action2 setAuthenticationRequired:NO];
        
        UIMutableUserNotificationCategory *actionCategory;
        actionCategory = [[UIMutableUserNotificationCategory alloc] init];
        [actionCategory setIdentifier:NotificationCategoryIdent];
        [actionCategory setActions:@[action1, action2]
                        forContext:UIUserNotificationActionContextDefault];
        
        NSSet *categories = [NSSet setWithObject:actionCategory];
        UIUserNotificationType types = (UIUserNotificationTypeAlert|
                                        UIUserNotificationTypeSound|
                                        UIUserNotificationTypeBadge);
        
        UIUserNotificationSettings *settings;
        settings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        
    } else {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|
                                                                       UIRemoteNotificationTypeSound|
                                                                       UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }
#else
    UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|
                                                                   UIRemoteNotificationTypeSound|
                                                                   UIRemoteNotificationTypeBadge);
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
#endif
    
}

- (void)registerPushCenterWithHandleBlock:(HandleRegisterBlock)block {
    self.regisierblock = block;
    [self registerRemoteNotification];
}


- (void)active:(NSError **)err {
    
    //[1-1]: 启动SDK
    [GeTuiSdk startSdkWithAppId:kAppId appKey:kAppKey appSecret:kAppSecret delegate:self error:err];
    
    if (!self.haveInit) {
        self.haveInit = YES;
        //[1-2]:设置是否后台运行开关
        [GeTuiSdk runBackgroundEnable:YES];
        //[1-3]:设置电子围栏功能，开启LBS定位服务 和 是否允许SDK 弹出用户定位请求
        [GeTuiSdk lbsLocationEnable:YES andUserVerify:YES];
    }
    
    if (err) {
        DYISocketLog(@"Err GeTuiSdk startSdk %@",[*err localizedDescription]);
    }
}
- (void)sleep{
    [GeTuiSdk enterBackground];
}

//- (NSError *)switchPushType:(TPushType) aType {
//    NSError * err = nil;
//    if (aType == EPushInside) {
//        [GeTuiSdk startSdkWithAppId:kAppId appKey:kAppKey appSecret:kAppSecret delegate:self error:&err];
//    } else {
//        [GeTuiSdk enterBackground];
//    }
//    NSLog(@"%@",err);
//    return err;
//}
#pragma mark-桥接自AppDelegate－对接sendProtocol-----消息DataCenter_BIND_STATE_ToDYPushCenter---------------------------


- (void)openPushCenter {
    //    self.openblock = block;
    [GeTuiSdk setPushModeForOff:NO];
}

- (void)closePushCenter {
    //    self.closeblock = block;
    [GeTuiSdk setPushModeForOff:YES];
}


#pragma mark-桥接自AppDelegate－用于注册--------------------------------
+ (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    [DYPushCenter sharedDYPushCenter].deviceToken = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    //    NSLog(@"APN 注册成功：deviceToken:%@", [DYPushCenter sharedDYPushCenter].deviceToken);
    // [3]:向个推服务器注册 deviceToken
    [GeTuiSdk registerDeviceToken:[DYPushCenter sharedDYPushCenter].deviceToken];
}

+ (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //    NSLog(@"APN 注册失败：err:%@", error);
    // [3-EXT]:如果 APNS 注册失败,通知个推服务器
    [GeTuiSdk registerDeviceToken:@""];
    if ([DYPushCenter sharedDYPushCenter].regisierblock) {
        [DYPushCenter sharedDYPushCenter].regisierblock(nil,error);
    }
}
#pragma mark TODO
+ (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // [2-EXT]: 启动时收到的 APN 数据  但是暂未发现起作用 后续查看
    //    NSDictionary*message=[launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    //    if (message) {
    //        NSString *payloadMsg = [message objectForKey:@"payload"];
    //        NSString *record = [NSString stringWithFormat:@"[APN]%@",
    //                            payloadMsg];
    //        //        [_viewController logMsg:record];
    //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"有远程推送的数据FinishLaunching" message:record delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    //        [alertView show];
    //    }
    return YES;
}

+ (void)applicationDidBecomeActive:(UIApplication *)application {
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [[DYPushCenter sharedDYPushCenter] active:nil];
}

+ (void)applicationDidEnterBackground:(UIApplication *)application {
    //通知个推 SDK 进入后台
    [[DYPushCenter sharedDYPushCenter] sleep];
}

#pragma mark -GeTuiSdkDelegate
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    DYISocketLog(@"注册个推成功 唯一标示clientId：%@",clientId);
    // [4-EXT-1]: 个推 SDK 已注册,返回 clientId
    self.clientId = clientId;
    if (self.regisierblock) {
        self.regisierblock(self.clientId, nil);
    }
    
    //个推有bug，根据个推要求 加这条
    if (_deviceToken) {
        [GeTuiSdk registerDeviceToken:_deviceToken];
    }
    //TODO 写入文件  实例类的时候 文件读取
}

#pragma mark TODO 暂时只打印
//无法确定 这个都报 什么错 暂时只打印搁置
- (void)GeTuiSdkDidOccurError:(NSError *)error {
    //    if (self.regisierblock) {
    //        self.regisierblock(nil,error);
    //    }
    DYISocketLog(@"个推报错:%@",[error localizedDescription]);
}

#pragma mark TODO 并未使用 暂时用于debug 考虑提供状态通知
//接收SDK状态
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus { // [EXT]:通知 本地的个推的 运行状态
    
    NSArray *arr = @[@"正在启动",@"启动",@"停止"];
    DYISocketLog(@"!!!个推状态:%@",arr[aStatus]);
}

#pragma -mark 收到个推的透穿消息
-(void)GeTuiSdkDidReceivePayload:(NSString*)payloadId andTaskId:(NSString*)taskId andMessageId:(NSString *)aMsgId fromApplication:(NSString *)appId{
    //[4]: 收到个推消息
    
    self.payloadId = payloadId;
    NSData* payload = [GeTuiSdk retrivePayloadById:payloadId]; //根据 payloadId 取回 Payload
    NSString *payloadMsg = nil;
    if (payload) {
        payloadMsg = [[NSString alloc] initWithBytes:payload.bytes
                                              length:payload.length encoding:NSUTF8StringEncoding];
    }
    NSString *record = [NSString stringWithFormat:@"%@", payloadMsg];
    DYISocketLog(@"task id : %@, messageId:%@,record: %@,payloadMsg: ", taskId, aMsgId,record,payloadMsg);
    [DYSMSCenter sendMessage:payloadMsg byType:DYPushCenter_Message];
}

- (void) addMessagePushReceiver:(id<DYSMSProtocol>) aRecerver {
    //添加接收者到指定的通知类型
    [DYSMSCenter addRecever:aRecerver withSMSType:DYPushCenter_Message];
}
- (void) removeMessagePushReceiver:(id<DYSMSProtocol>) aRecerver {
    [DYSMSCenter removeReceiver:aRecerver withSMSType:DYPushCenter_Message];
}
@end
